﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.WebPages;

namespace MvcToolbox
{
    public static class ForEachEditorExtension
    {

        /// <summary>
        /// Fors the each editor.
        /// </summary>
        /// <example>
        ///   @Html.ForEachEditor(m => m.Items,@<span>
        ///      @Html.EditorFor(p => p.Items[item.Index])
        ///      </span>);
        /// </example>
        /// <typeparam name="TModel">The type of the T model.</typeparam>
        /// <typeparam name="TProperty">The type of the T property.</typeparam>
        /// <param name="html">The HTML.</param>
        /// <param name="expression">The expression.</param>
        /// <param name="render">The render.</param>
        /// <returns>IHtmlString.</returns>
        public static IHtmlString ForEachEditor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, List<TProperty>>> expression, Func<ForEachModel<TProperty>, HelperResult> render)
        {
            StringBuilder sb = new StringBuilder();
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            List<TProperty> values = metadata.Model as List<TProperty>;
            int count = 0;
            foreach (var val in values)
            {
                sb.Append(render(new ForEachModel<TProperty>(val, count++)).ToHtmlString());
            }
            return new HtmlString(sb.ToString());
        }
    }

    public class ForEachModel<T>
    {
        public T Model { get; set; }
        public int Index { get; set; }

        public ForEachModel(T model, int index)
        {
            Model = model;
            Index = index;
        }
    }
}